import { Image, classRegistry, util } from 'fabric';
import 'gifler';

export class GifImage extends Image {
	constructor(element, options) {
        super(element, options);
        this.gifCanvas = undefined;
        this.gifler = undefined;
        this.isStarted = false;
        this.gifCanvas = document.createElement('canvas');
    }

	drawFrame(ctx, frame) {
        
		if (!this.gifCanvas) return
		this.gifCanvas.width = frame.width
		this.gifCanvas.height = frame.height
		ctx.drawImage(frame.buffer, 0, 0)
		this.setSrc(this.gifCanvas.toDataURL())
		this.canvas?.renderAll();
	}

	_render(ctx) {
        super._render(ctx);
        this.dirty = true;
        if (!this.isStarted) {
            this.isStarted = true;
            this.gifler = window.gifler(this.getSrc()).frames(this.gifCanvas, (context, frame) => {
                this.isStarted = true;
                this.drawFrame(context, frame);
            });
        }
    }
    fromURL(url, options = {}) {
        return util.loadImage(url, options).then((img) => new this(img, options));
    }
}

classRegistry.setClass(GifImage)
